package com.weixin.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.weixin.util.FileUtil;
import com.weixin.util.GsonUtil;
import com.weixin.util.HttpTools;
import com.weixin.vo.AccessTokenResponse;
import com.weixin.vo.LoginUser;
import com.weixin.vo.TXUserInfo;

/**
 * Servlet implementation class ReceiveServlet
 */
public class LoginServlet extends HttpServlet {
	Logger logger = Logger.getLogger(LoginServlet.class);
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String authURL = "https://open.weixin.qq.com/connect/oauth2/authorize?"
					+ "appid=wx1c46a911075e0f90"
					+ "&redirect_uri=http://www.uuerp.cn/verp3/login"
					+ "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			
			//能娶到当前session
			  // if(能)
				 //main.html
			  // else
				//先或则用户授权，获取openid
				
				//然后查询是否绑定用户,没绑定去登陆页
			String code = request.getParameter("code");
			logger.debug("code:"+code);
			
			String sessioncode  = (String)request.getSession().getAttribute("code");
			logger.debug("session code:"+sessioncode);
			/**
			 * 	
			TXUserInfo u = new TXUserInfo();
			u.setNickname("dd");
			request.getSession().setAttribute("user", u);
			
			FileUtil.appendWrite(GsonUtil.toJson(u));
			 * 
			 */
			 
			if(request.getSession().getAttribute("user") !=null){
				TXUserInfo user =(TXUserInfo) request.getSession().getAttribute("user");
				logger.debug("session user is not null:"+GsonUtil.toJson(user));
				
				//
				com.weixin.util.CacheMap.init();
				System.out.println(GsonUtil.toJson(com.weixin.util.CacheMap.map));
				
				response.sendRedirect("main.jsp");
			}else{
				
				if(StringUtils.isNoneEmpty(request.getParameter("username"))||
						StringUtils.isNoneEmpty(request.getParameter("password"))){
					LoginUser loginUser = new LoginUser();
					loginUser.setUsername(request.getParameter("username"));
					loginUser.setPassword(request.getParameter("password"));
					request.getSession().setAttribute("loginUser", loginUser);
					if(StringUtils.isNotEmpty(code)){
						
					}else{
						logger.debug("when user login ,code is null,start auth:"+authURL);
						response.sendRedirect(authURL);
						return;
					}
				}
					
				if(!"".equals(code) && null != code){
					request.getSession().setAttribute("code",code);
					
					String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
							+ "appid=wx1c46a911075e0f90"
							+ "&secret=c51df92c57b4402bf2761294f3a0b276"
							+ "&code="+code+"&grant_type=authorization_code";
					
					
					String accessTokenResponseString = HttpTools.getInstance().sendHttpRequest(get_access_token_url, null);
					logger.debug("accessTokenResponseString:"+accessTokenResponseString);
					
					
					AccessTokenResponse atr = (AccessTokenResponse)	GsonUtil.fromJson(accessTokenResponseString, AccessTokenResponse.class);
					
					logger.debug("AccessTokenResponse's openid is:"+atr.getOpenid());
					
					if(StringUtils.isNotEmpty(atr.getOpenid())){
						
						TXUserInfo cacheUser  = com.weixin.util.CacheMap.map.get(atr.getOpenid());
						if(cacheUser !=null){
							LoginUser loginU = cacheUser.getLoginUser();
							if(loginU ==null){
								response.sendRedirect("login.html");
							}else{
								request.getSession().setAttribute("user", cacheUser);
								response.sendRedirect("main.jsp");
							}
							
						}else{
							
							String user_url ="https://api.weixin.qq.com/sns/userinfo?"
									+ "access_token="+atr.getAccess_token()
									+"&openid="+atr.getOpenid();
							
							String userInfoString = HttpTools.getInstance().sendHttpRequest(user_url, null);
							logger.debug("userInfoString:"+userInfoString);
							
							
							TXUserInfo userObj =  (TXUserInfo)	GsonUtil.fromJson(userInfoString, TXUserInfo.class);
							
							LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
							if(loginUser !=null){
								userObj.setLoginUser(loginUser );
								request.getSession().setAttribute("user", userObj);

								FileUtil.appendWrite(GsonUtil.toJson(userObj));
								response.sendRedirect("main.jsp");
							}else{
								response.sendRedirect("login.html");
							}
						}
					}
					
				}else{
					logger.debug("code is null,start auth:"+authURL);
					response.sendRedirect(authURL);
				}
				
			}
		} catch (Exception e) {
			logger.error(e,e);
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		
	}

}
